package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClint1 {
    private DatagramSocket socket = null;
    //这里要构造服务器的ip和端口
    private String serverIp;
    private int serverPort;
    //客户端在启动时需要只要服务器在哪！！
    public UdpEchoClint1(String serverIp,int serverPort) throws SocketException {
        socket = new DatagramSocket();//客户端不需要一个显示关联的端口号，这个端口是操作系桶自动分配的
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    //客户端启动时需要执行的主逻辑
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String request = scanner.next();
            //把字符串构造成UDP packet 然后进行发送请求到服务器那里
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);

            //3.客户端发送之后，服务器进行响应回来，客户端尝试读取响应的数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.再把接收过来的数据转换成一个String 字符串
            String response = new String(responsePacket.getData(),0,requestPacket.getLength());
            //打印日志
            System.out.printf("req: %s, resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClint1 udpEchoClint1 = new UdpEchoClint1("127.0.0.1",999);
        udpEchoClint1.start();
    }
}
